/*!
 * @file DFRobot_esp8266_Pub.ino
 * @brief DFRobot's publish data to the server.
 * @n [Get the module here](http://www.dfrobot.com/index.php?route=product/product&product_id=1088)
 * @n This example publish to the data from the server.
 * @n [Connection and Diagram]
 *
 * @copyright	[DFRobot](http://www.dfrobot.com), 2016
 * @copyright	GNU Lesser General Public License
 *
 * @author [Wuxiao](Xiao.wu@dfrobot.com)
 * @version  V0.0.2
 * @date  2016-11-4
 */
#include <ESP8266WiFi.h>
#include "Iot.h"

WiFiClient client;

#define WLAN_SSID       "yourNetwork"      ///< your network SSID (name)
#define WLAN_PASS       "secretPassword"   ///< your network password

#ifdef ARDUINO_ESP8266_DFRobot_Education   ///< Choosing the condition, DFRobot server will be connected
#define AIO_USERNAME    "test"
#define AIO_KEY         "test"
Iot iot(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
#elif defined ARDUINO_ESP8266_DFRobot              ///< Choosing the condition, 10086 cloud server will be connected
#define AIO_USERNAME    "72833"
#define AIO_KEY    "sub123456"
#define AIO_CLIENTID    "3369569"
Iot iot(&client, AIO_SERVER, AIO_SERVERPORT, AIO_CLIENTID, AIO_USERNAME, AIO_KEY);
#endif

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println(F("DFrobot MQTT demo"));
  Serial.println(); 
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  
  /*!
   *  @brief set your's publish topic 
   */
  if(iot.publish("temp")){
	  Serial.printf("set publish topic ok!\n");
  }
  
}

int x=0;
void loop() {

  if(iot.connected()){
	  Serial.printf("already connected!\n");
  }else{
	  iot.connect();
  }	   
  iot.writeInt("temp",x);
  iot.writeString("onoff","on");
  double test = 21.51;
  iot.writeDouble("change",test);
  x++;
  
  /*!
   *  @brief Flush temp data  
   */
  if(iot.flush("temp")){
	  Serial.printf("Pub OK!\n");
  }else{
	  Serial.printf("Pub Error!\n");  
  }
  
  delay(2000);
}


